//
//  HeadLabelsView.m
//  ArtDog
//
//  Created by dllo on 16/9/9.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "HeadLabelsView.h"
#import "UIColor+Common.h"
#import "Masonry.h"
#import "HLMacro.h"

#define WIDTH self.frame.size.width
#define HEIGHT self.frame.size.height

@interface HeadLabelsView ()

@property (nonatomic, strong) UIView *lineView;

@end

@implementation HeadLabelsView
- (void)setTitles:(NSArray *)titles
{
    _titles = titles;
    [self setupViews];
    [self layoutAllViews];
}

- (void)setupViews
{
    for (int i = 0; i < _titles.count;i ++) {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        [self addSubview:button];
        button.tag = 100 + i;
        [button setTitle:_titles[i] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        if (button.tag == 100) {
            [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        } else {
            [button setTitleColor:[UIColor colorFromHexRGB:@"8a8a8a"] forState:UIControlStateNormal];
        }
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    _lineView = [[UIView alloc]initWithFrame:CGRectMake((1.0/_titles.count + 2.0/_titles.count * (100 - 100)) * WIDTH / 2 - 17, HEIGHT - 1, 34, 1)];
    [self addSubview:_lineView];
    _lineView.backgroundColor = [UIColor blackColor];
    
}

- (void)layoutAllViews
{
    for (int i = 0; i < _titles.count; i++) {
        UIButton *button = [self viewWithTag:i + 100];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self);
            make.centerX.equalTo(self).multipliedBy(1.0/_titles.count + 2.0/_titles.count * i);
        }];
    }
}

#pragma mark - button clicked
- (void)buttonAction:(UIButton *)button
{
    if (_lineView.frame.origin.x != (1.0/_titles.count + 2.0/_titles.count * (button.tag - 100)) * WIDTH / 2 - 17) {
        for (int i = 0; i < _titles.count; i++) {
            UIButton *aButton = [self viewWithTag:i + 100];
            [aButton setTitleColor:[UIColor colorFromHexRGB:@"8a8a8a"] forState:UIControlStateNormal];
        }
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            _lineView.frame = CGRectMake((1.0/_titles.count + 2.0/_titles.count * (button.tag - 100)) * WIDTH / 2 - 17, HEIGHT - 1, 34, 1);
        } completion:nil];
        if (_collectionViewOffset) {
            _collectionViewOffset((button.tag - 100)*SCREEN_WIDTH);
        }
    }
}

- (void)setButtonSelect:(NSInteger)index
{
    [self buttonAction:[self viewWithTag:index + 100]];
}


@end
